package com.zrulin.ftcommunity.config;

import com.zrulin.ftcommunity.util.CommunityConstant;
import com.zrulin.ftcommunity.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zrulin
 * @create 2022-07-11 15:52
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略静态资源的访问
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权
        http.authorizeRequests()
                .antMatchers(
                        "/discuss/add",
                        "/follow",
                        "/unfollow",
                        "/letter/**",
                        "/notice/**",
                        "/activity/add",
                        "/comment/**",
                        "/like/click",
                        "/team/status",
                        "/team/add",
                        "/user/setting",
                        "/user/headerImage",
                        "/user/updatePassword",
                        "/team/detail/**"
                ).hasAnyAuthority(
                        AUTHORITY_USER,
                        AUTHORITY_ADMIN,
                        AUTHORITY_MODERATOR
                ).antMatchers(
                        "/discuss/wonderful"
                ).hasAnyAuthority(
                        AUTHORITY_MODERATOR
                ).antMatchers(
                        "/discuss/top",
                            "/discuss/delete",
                        "/admin/**"
                ).hasAnyAuthority(
                        AUTHORITY_ADMIN
                ).anyRequest().permitAll().and().csrf().disable();//禁用csrf检查

        //权限不够时的处理
        http.exceptionHandling()
                .authenticationEntryPoint(new AuthenticationEntryPoint() {//没有登录时怎么处理
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        //判断是普通请求还是异步请求，也就是说判断是返回json数据还是返回html页面。
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xRequestedWith)){//如果是这个值，那么就判断为异步请求。
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJsonString(403, "您还没有登录哦！"));
                        }else {//不是这个值就是同步请求
                            response.sendRedirect(request.getContextPath() + "/login");
                        }
                    }
                })
                .accessDeniedHandler(new AccessDeniedHandler() {//登录了，但是权限不足怎么处理。
                    @Override
                    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                        //判断是普通请求还是异步请求，也就是说判断是返回json数据还是返回html页面。
                        String xRequestedWith = request.getHeader("x-requested-with");
                        if("XMLHttpRequest".equals(xRequestedWith)){//如果是这个值，那么就判断为异步请求。
                            response.setContentType("application/plain;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write(CommunityUtil.getJsonString(403, "你没有访问此功能的权限！"));
                        }else {//不是这个值就是同步请求
                            response.sendRedirect(request.getContextPath() + "/denied");
                        }
                    }
                });
        //Security 底层会默认拦截/logout请求，进行退出处理，它的底层是一个一个Filter,在DispatcherServlet前面，自然Controller前面
        //这样我们自己写的/logout就不会在执行了。覆盖它底层的逻辑，才能执行我们自己的代码。
        http.logout().logoutUrl("/securitylogout");//做一个善意的欺骗。

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    }
}
